package com.itheima.reggie.controller;

import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.common.R;
import com.itheima.reggie.pojo.ShoppingCart;
import com.itheima.reggie.service.ShoppingCartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 购物车管理
 */
@RestController
@RequestMapping("shoppingCart")
public class ShoppingCartController {

    @Autowired
    ShoppingCartService shoppingCartService;

    /**
     * 购物车新增菜品
     */
    @PostMapping("add")
    public R<ShoppingCart> add(@RequestBody ShoppingCart shoppingCart) {
        //1. 判断购物车是否包含菜品或者套餐
        ShoppingCart cart = shoppingCartService.query()
                .eq("user_id", BaseContext.getCurrentId())
                .eq(shoppingCart.getDishId() != null, "dish_id", shoppingCart.getDishId())
                .eq(shoppingCart.getSetmealId() != null, "setmeal_id", shoppingCart.getSetmealId())
                .one();
        if (cart != null) {
            //说明购物车包含商品， +1，更新操作
            cart.setNumber(cart.getNumber() + 1);
            shoppingCartService.updateById(cart);
            return R.success(cart);
        } else {//说明购物车不包含商品， 添加操作
            shoppingCart.setUserId(BaseContext.getCurrentId());
            shoppingCart.setCreateTime(LocalDateTime.now());
            shoppingCart.setNumber(1);  //设置数量 默认1
            shoppingCartService.save(shoppingCart);
            return R.success(shoppingCart);
        }
    }

    /**
     * 查询购物车菜品
     */
    @GetMapping("list")
    public R<List<ShoppingCart>> list() {
        List<ShoppingCart> list = shoppingCartService.query()
                .eq("user_id", BaseContext.getCurrentId())
                .list();
        return R.success(list);
    }

    /**
     * 删除购物车菜品
     */
    @PostMapping("sub")
    public R<ShoppingCart> sub(@RequestBody ShoppingCart shoppingCart) {
        ShoppingCart cart = shoppingCartService.query()
                .eq("user_id", BaseContext.getCurrentId())
                .eq(shoppingCart.getDishId() != null, "dish_id", shoppingCart.getDishId())
                .eq(shoppingCart.getSetmealId() != null, "setmeal_id", shoppingCart.getSetmealId())
                .one();
        if (cart.getNumber() <= 1) {
            cart.setNumber(0);
            shoppingCartService.removeById(cart.getId());
            return R.success(cart);

        } else {
            cart.setNumber(cart.getNumber() - 1);
            shoppingCartService.updateById(cart);
            return R.success(cart);
        }
    }

    /**
     * 清空购物车菜品
     */
    @DeleteMapping("clean")
    public R<String> clean() {
        shoppingCartService.update()
                .eq("user_id", BaseContext.getCurrentId())
                .remove();
        return R.success("");
    }


}
